package com.study.www.service;

import com.study.www.config.IdWorks;
import com.study.www.entity.Dept;
import com.study.www.repository.DeptRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 *  使用  JPA
 * @author : Administrator.zhuyanpeng
 * @date : 2019/11/1 - 14:30
 */
@Service
@Slf4j
public class DeptJpaService {
    @Autowired
    DeptRepository deptRepository;

    public Dept save(Dept dept){
        dept.setId(IdWorks.getId());
        dept.setCreateTimeLong(System.currentTimeMillis()+"");
        dept.setSalary(dept.getSalary()*1000);
        Dept save = deptRepository.save(dept);
        log.warn(save.toString());
        return save;
    }

    public String saveOrChange(Dept dept){
        if (dept.getId() == null || "".equals(dept.getId())){
            Dept save = this.save(dept);
            return save.getId();
        }
        Optional<Dept> optionalDept = deptRepository.findById(dept.getId());
        optionalDept.orElseThrow(() -> new RuntimeException("该部门未找到"));
        String id = optionalDept.get().getId();
        dept.setId(id);
        dept.setCreateTimeLong(optionalDept.get().getCreateTimeLong());
        this.save(dept);
        return id;
    }

    public Dept findById(String id){
        return deptRepository.findById(id).orElseGet(() -> null);
    }

    /**
     * hashCode  等于查询
     * startWith search%
     * endsWith  %search
     * @param name 名称
     * @return
     * @throws
     * @author zhuyanpeng
     * @date 2019/11/1
     */
    public List<Dept> queryByName(String name){
        Dept dept = new Dept();
        dept.setName(name);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.endsWith());
        Example<Dept> example = Example.of(dept, matcher);
        return  deptRepository.findAll(example);
    }

    /**
     *  使用 Example 去做分页查询处理
     * 获得 mongodb 中mobile以查询条件开头的分页
     */
    public Page<Dept> queryPageAndMobile(String mobile, Integer startInt, Integer endInt){
        PageRequest pageRequest = PageRequest.of(startInt, endInt, Sort.Direction.DESC, "id");
        Dept dept = new Dept();
        dept.setMobile(mobile);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("mobile", ExampleMatcher.GenericPropertyMatchers.startsWith());
        Example<Dept> example = Example.of(dept, exampleMatcher);
        return  deptRepository.findAll(example, pageRequest);
    }


}
